package team.nmsg.ge.system.init.https;

import java.io.File;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import team.nmsg.ge.system.util.ServerParams;


//@Configuration
public class HttpsConfig {

//	@Bean
//	public EmbeddedServletContainerCustomizer containerCustomizer() {
//		return new EmbeddedServletContainerCustomizer() {
//			@Override
//			public void customize(ConfigurableEmbeddedServletContainer container) {
//				Ssl ssl = new Ssl();
//				// Server.jks中包含服务器私钥和证书
//				ssl.setKeyStore("keystore.p12");
//				ssl.setKeyStorePassword("123456");
//				ssl.setKeyStoreType("PKCS12");
//				container.setSsl(ssl);
//				container.setPort(8443);
//			}
//		};
//	}
	
	@Value("${server.port}")
	private int serverPort;
	
	@Value("${server.http.port}")
	private int serverHttpPort;
	
	@Bean
	public EmbeddedServletContainerFactory servletContainerFactory() {
		TomcatEmbeddedServletContainerFactory factory =
				new TomcatEmbeddedServletContainerFactory() {
			@Override
			protected void postProcessContext(Context context) {
				//SecurityConstraint必须存在，可以通过其为不同的URL设置不同的重定向策略。
				SecurityConstraint securityConstraint = new SecurityConstraint();
				securityConstraint.setUserConstraint("CONFIDENTIAL");
				SecurityCollection collection = new SecurityCollection();
				collection.addPattern("/*");
				securityConstraint.addCollection(collection);
				context.addConstraint(securityConstraint);
			}
		};
		factory.setDocumentRoot(new File(ServerParams.BASIC_STATIC_DIR));
		factory.addAdditionalTomcatConnectors(createHttpConnector());
		return factory;
	}

	private Connector createHttpConnector() {
	    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
	    connector.setScheme("http");
	    connector.setSecure(false);
	    connector.setPort(serverHttpPort);
	    connector.setRedirectPort(serverPort);
	    return connector;
	}

}
